package com.lanou.bbs.util;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;

/**
 * 加载数据库配置文件
 * 需在src路径下才可以用
 * 配置文件名是JDBCProp.properties
 * 文件内数据库等其他内容自己定义
 * 记住,所有Controller层第一句开启事务,最后一句关资源,中间正常写
 */
public class JDBCUtil {
    private static ThreadLocal<Connection> threadLocal
            = new ThreadLocal<>();
    private static String driverClass;
    private static String url;
    private static Properties info = new Properties();

    //加载驱动
    static {
        try {
            InputStream is = JDBCUtil.class.getClassLoader().getResourceAsStream("JDBCProp.properties");
//            System.out.println(JDBCUtil.class.getClassLoader());
            info.load(is);
            driverClass = info.getProperty("driverClass");
            url = info.getProperty("url");
            Class.forName(driverClass);//通过这个代码调用了注册驱动的静态代码
            IOClose.closeAll(is);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    //执行SQL语句
    public static MyStatement getStatement(String sql) {
        Connection conn = getConn();
        try {
            PreparedStatement ps = conn.prepareStatement(sql);
            return new MyStatement(ps);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    //获取conn
    public static Connection getConn() {
        try {
            Connection conn = threadLocal.get();//尝试从threadLocal中取出Connection
            //没有conn对象,则证明并没有
            if (conn == null) {
                conn = DriverManager.getConnection(url, info);//没有则创建一个conn对象
                threadLocal.set(conn);//存到threadLocal中
            }
            return conn;
        } catch (SQLException e) {
            throw new RuntimeException(e);//编译时异常 改成 运行时异常 (上边那个可以一起写)
        }
    }

    //开启事务
    public static void begin() {
        Connection conn = getConn();
        try {
            conn.setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //关闭 conn 和 事务
    //至于是否回滚,在你执行sql语句时进行判断
    public static void closeConn() {
        Connection conn = threadLocal.get();
        if (conn != null) {
            try {
                if (!conn.getAutoCommit()){
                    //如果开启了事务,那么提交事务
                    conn.commit();
                }
                conn.close();
                threadLocal.remove();//把这个conn从threadLocal中清除
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
